package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.PoiItem;
import com.sgb.alimaplibrary.widget.MapMarkerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.view.ui.adapter.MapAdressAdapter;
import com.swgk.core.dialog.BaseBottomDialog;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.DialogViewHolder;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration;
import com.swgk.core.util.MToast;

/**
 * 选择地址地图dialog
 */
public class MapAdressDialog extends BaseBottomDialog{
    private LatLng mFinalLatLng = new LatLng(0, 0);
    private View markerView;

    // 初始化全局 bitmap 信息，不用时及时 recycle
    private BitmapDescriptor bitmapSmall = BitmapDescriptorFactory.fromResource(R.mipmap.img_mark);

    TextView tvCancel;
    TextView tvSure;
    EditText etSearch;
    RecyclerView rvList;
    MapMarkerView mMapView;

    private String currentCity = "北京市";
    public static final String CITY = "city";
    public static final String LATITUDE = "latitude";
    public static final String LONGTITUDE = "longtitude";
    public static final String ADDRESS = "address";
    private String address;
    private String City;
    private String Pro;
    private String Area;
    DialogClickCallBack dialogClickCallBack;
    MapAdressAdapter adressAdapter;

    private int pos = 0;
    public MapAdressDialog(Context context, DialogCallBack dialogCallBack) {
        super(context, dialogCallBack);
    }

    public MapAdressDialog(Context context, int theme, DialogCallBack dialogCallBack) {
        super(context, theme, dialogCallBack);
    }

    @Override
    protected int dialogLayout() {
        return R.layout.dialog_select_adress;
    }

    @Override
    protected void initView(DialogViewHolder holder,Bundle savedInstanceState) {
        tvCancel=holder.getDialog().findViewById(R.id.tv_cancel);
        tvSure=holder.getDialog().findViewById(R.id.tv_sure);
        etSearch=holder.getDialog().findViewById(R.id.searchAddress);
        mMapView=holder.getDialog().findViewById(R.id.mMapView);
        rvList=holder.getDialog().findViewById(R.id.rv_list);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        adressAdapter=new MapAdressAdapter(getContext(),mMapView.getPoiItems());
        rvList.addItemDecoration(new RecyclerViewItemDecoration(getContext().getResources().getDimension(R.dimen.dp10)));
        rvList.setAdapter(adressAdapter);
        adressAdapter.setOnItemClick(new AdapterOnItemClick<PoiItem>() {
            @Override
            public void onItemClick(PoiItem poiInfo, int position) {
                address=poiInfo.getSnippet();
                Pro=poiInfo.getProvinceCode();
                City=poiInfo.getCityCode();
                Area=poiInfo.getAdCode();
                adressAdapter.setSelsect(position);
                showMarkerView(position,"");
            }
        });
        etSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    String keyword=etSearch.getText().toString();
                    if (TextUtils.isEmpty(keyword)) {
                        MToast.showToast(getContext(), "请输入关键字");
                        return true;
                    }
                    hideKeyboard();
                    setPoiSearchOption(keyword);
                }
                return false;
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(dialogClickCallBack!=null){
                    dialogClickCallBack.onClickMarker(address,Pro,City,Area,mFinalLatLng.latitude,mFinalLatLng.longitude);
                }
                dismiss();

            }
        });
        if (savedInstanceState!=null){
            initView(savedInstanceState);
        }
    }

    private void initView(Bundle savedInstanceState) {
        initMap(savedInstanceState);
        mMapView.setMapClick();;
    }

    private void initMap(Bundle savedInstanceState) {
        mMapView.initMap(savedInstanceState, null, new MapMarkerView.CallBack() {
            @Override
            public void onMarkerClick(int pos, String title) {
                showMarkerView(pos,title);
            }

            @Override
            public void onLocation(Double Lat, Double Log, String string) {
                if (mFinalLatLng.longitude != 0 && mFinalLatLng.latitude !=0) return;
                mFinalLatLng = new LatLng(Lat, Log);
                adressAdapter.setDatas(mMapView.getPoiItems());
            }

            @Override
            public void getAddress(Double Lat, Double Log,String address) {
                super.getAddress(Lat,Log,address);
                mFinalLatLng = new LatLng(Lat, Log);
                adressAdapter.setDatas(mMapView.getPoiItems());
            }

            @Override
            public void onRegeocodeSearched(Double Lat, Double Log, String string) {
                super.onRegeocodeSearched(Lat,Log,string);
                pos = 0;
                showMarkerView(pos,"");
            }
        });
    }

    private void showMarkerView(int pos, String title) {
            PoiItem poiItem = mMapView.getPoiItems().get(pos);
            mFinalLatLng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
            mMapView.setMarkerIcon(pos,true);
            address = poiItem.getSnippet();
            Pro=poiItem.getProvinceCode();
            City=poiItem.getCityCode();
            Area=poiItem.getAdCode();
            double la=poiItem.getLatLonPoint().getLatitude();
            double lo=poiItem.getLatLonPoint().getLongitude();
            mFinalLatLng=new LatLng(la,lo);
            adressAdapter.setDatas(mMapView.getPoiItems());
    }

    public interface DialogClickCallBack {
        void onClickMarker(String adress,String pro,String city,String area,double latitude, double longtitude );
    }

    public void setDialogClickCallBack(DialogClickCallBack dialogClickCallBack) {
        this.dialogClickCallBack = dialogClickCallBack;
    }

    @Override
    public void setOnDismissListener(@Nullable OnDismissListener listener) {
        super.setOnDismissListener(listener);
    }
    public void setLocation( double latitude, double longtitude ){
        mFinalLatLng = new LatLng(latitude, longtitude);
        mMapView.getLatLotExtra(latitude,longtitude);
    }

    /**
     * PoiCiySearchOption 设置检索属性
     * city 检索城市
     * keyword 检索内容关键字
     * pageNum 分页页码
     */
    private void setPoiSearchOption(String keyword) {
        DialogHelper.showProgressDialog(getContext(), "搜索中...", 0, false);
        mMapView.setPoiSearch(keyword,"");
    }

    public void destoryMap(){
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (bitmapSmall != null) {
            bitmapSmall.recycle();
        }
        if (mMapView != null) {
            mMapView.deactivate();
        }
        mMapView.onDestroy();
    }
    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }
}
